package generator.service.impl;

import com.atkt.ktkt.model.activity.CouponInfo;
import com.atkt.ktkt.model.order.OrderDetail;
import com.atkt.ktkt.model.order.OrderInfo;
import com.atkt.ktkt.model.user.UserInfo;
import com.atkt.ktkt.model.vod.Course;
import com.atkt.ktkt.vo.order.OrderFormVo;
import com.atkt.ktkt.vo.order.OrderInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktkt.client.course.CourseFeignClient;
import com.ktkt.client.user.UserInfoFeignClient;
import com.ktkt.client.activity.CouponInfoFeignClient;
import generator.service.OrderDetailService;
import generator.service.OrderInfoService;
import generator.mapper.OrderInfoMapper;
import ktkt.exception.GgktException;
import ktkt.result.ResultCodeEnum;
import ktkt.utils.AuthContextHolder;
import ktkt.utils.OrderNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 罗雅文
 * @description 针对表【order_info(订单表 订单表)】的数据库操作Service实现
 * @createDate 2022-09-23 14:54:02
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo>
        implements OrderInfoService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private CourseFeignClient courseFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private CouponInfoFeignClient couponInfoFeignClient;

    //订单列表
    @Override
    public Map<String, Object> selectOrderInfoPage(Page<OrderInfo> orderInfoPage,
                                                   OrderInfoQueryVo orderInfoQueryVo) {
        // OrderInfoVo 获取查询条件
        Long userId = orderInfoQueryVo.getUserId();
        String outTradeNo = orderInfoQueryVo.getOutTradeNo();
        String phone = orderInfoQueryVo.getPhone();
        String createTimeEnd = orderInfoQueryVo.getCreateTimeEnd();
        String createTimeBegin = orderInfoQueryVo.getCreateTimeBegin();
        Integer orderStatus = orderInfoQueryVo.getOrderStatus();
        //判断条件值是否为空 不为空进行条件封装
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq(OrderInfo::getUserId, userId);
        }
        if (!StringUtils.isEmpty(outTradeNo)) {
            wrapper.eq(OrderInfo::getOutTradeNo, outTradeNo);
        }
        if (!StringUtils.isEmpty(phone)) {
            wrapper.eq(OrderInfo::getPhone, phone);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq(OrderInfo::getOrderStatus, orderStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge(OrderInfo::getCreateTime, createTimeBegin);  //大于等于
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le(OrderInfo::getCreateTime, createTimeEnd); //小于等于
        }
        // 调用实现分页 分页查询
        Page<OrderInfo> pages = baseMapper.selectPage(orderInfoPage, wrapper);
        long totalCount = pages.getTotal();
        long pagesCount = pages.getPages();
        List<OrderInfo> records = pages.getRecords();
        //订单里面包含详情内容 封装详情数据 根据订单id 查询详情
        records.stream().forEach(item -> {
            this.getOrderDetail(item);
        });

        //封装数据 返回所有值
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",totalCount);
        map.put("pageCount",pagesCount);
        map.put("records",records);
        return map;
    }

    //生成订单方法
    @Override
    public Long submitOrder(OrderFormVo orderFormVo) {
        //1.获取生成订单条件值
        Long courseId = orderFormVo.getCourseId(); //课程id
        Long couponId = orderFormVo.getCouponId(); //优惠卷id
        Long userId = AuthContextHolder.getUserId();

        //2.判断当前用户是否已经生成订单
        //课程id  用户id
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getCourseId, courseId);
        queryWrapper.eq(OrderDetail::getUserId, userId);
        OrderDetail orderDetailExist = orderDetailService.getOne(queryWrapper);
        if(orderDetailExist != null){
            return orderDetailExist.getId(); //如果订单已存在，则直接返回订单id
        }

        //3. 根据课程id 查询课程信息
        Course course = courseFeignClient.getById(courseId);
        if (course==null){
            throw  new GgktException(20001,"课程不存在");
        }

        //4. 根据用户id查询用户信息
        UserInfo userInfo = userInfoFeignClient.getById(userId);
        if (userInfo == null) {
            throw new GgktException(ResultCodeEnum.DATA_ERROR.getCode(),
                    ResultCodeEnum.DATA_ERROR.getMessage());
        }

        //5. 根据优惠卷id 查询优惠卷信息
        BigDecimal couponReduce = new BigDecimal(0);
        if(null != couponId) {
            CouponInfo couponInfo = couponInfoFeignClient.getById(couponId);
            couponReduce = couponInfo.getAmount();
        }

        //6. 封装订单生成需要数据到对象 完成添加订单
        //6.1 封装数据到OrderInfo 对象里面 添加订单基本信息表
        //创建订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userInfo.getNickName());
        orderInfo.setPhone(userInfo.getPhone());
        orderInfo.setProvince(userInfo.getProvince());
        orderInfo.setOriginAmount(course.getPrice());
        orderInfo.setCouponReduce(couponReduce);
        orderInfo.setFinalAmount(orderInfo.getOriginAmount().subtract(orderInfo.getCouponReduce()));
        orderInfo.setOutTradeNo(OrderNoUtils.getOrderNo());
        orderInfo.setTradeBody(course.getTitle());
        orderInfo.setOrderStatus("0");
        baseMapper.insert(orderInfo);

        // 6.2 封装数据到OrderDetail 对象里面 添加订单详细信息表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderInfo.getId());
        orderDetail.setUserId(userId);
        orderDetail.setCourseId(courseId);
        orderDetail.setCourseName(course.getTitle());
        orderDetail.setCover(course.getCover());
        orderDetail.setOriginAmount(course.getPrice());
        orderDetail.setCouponReduce(new BigDecimal(0));
        orderDetail.setFinalAmount(orderDetail.getOriginAmount().subtract(orderDetail.getCouponReduce()));
        orderDetailService.save(orderDetail);

        //7. 更新优惠卷状态
        if(null != orderFormVo.getCouponUseId()) {
            couponInfoFeignClient.updateCouponInfoUseStatus(orderFormVo.getCouponUseId(), orderInfo.getId());
        }
        //8. 返回订单id
        return orderInfo.getId();
    }

    //查询订单详细数据
    private OrderInfo getOrderDetail(OrderInfo orderInfo) {
        //根据订单id
        Long id = orderInfo.getId();
        //查询订单详细
        OrderDetail orderDetailById = orderDetailService.getById(id);
        if (orderDetailById!=null){
            String courseName = orderDetailById.getCourseName();
            orderInfo.getParam().put("courseName",courseName);  //继承了BasicEntity
        }
        return orderInfo;
    }
}




